package com.hmall.order.mq;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.dto.Item;
import com.hmall.feign.clients.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OrderRabbitListener {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "delay.queue",durable = "true"),
                    exchange = @Exchange(name = "delay.direct",delayed = "true"),
                    key = "delay"
            )
    )
    public void listenDelayedQueue(String msg) {
        System.out.println(msg + ",接收到延迟消息 来自delay.queue队列");
        Order order = orderService.getById(msg);
        if (order.getStatus() != 1 && order.getStatus() != 5) {
            //订单状态不为未支付也不为取消 即是2、已付款,未发货 3、已发货,未确认 4、确认收货，交易成功中的一种
            //直接结束方法 丢弃消息不管
            return;
        }
        //代码走到这里: 未完成支付
        order.setStatus(5);   //修改订单状态为取消
        orderService.updateById(order);
        LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(OrderDetail::getOrderId,order.getId());
        OrderDetail orderDetail = orderDetailService.getOne(qw);
        Integer num = orderDetail.getNum();

        Item item = itemClient.getItemById(orderDetail.getItemId());
        Integer stockNow = item.getStock() + num;
        item.setStock(stockNow);
        itemClient.updateItemInfo(item);
    }

}
